package Tree;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Tree
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-26  09:04
 * @Description: TODO
 * @Version: 1.0
 */
public class 求根节点到叶节点数字之和129 {

    int result = 0;

    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        traversal(root, new StringBuilder());
        return result;
    }

    private void traversal(TreeNode root, StringBuilder paths) {
        paths.append(root.val);
        if (root.left == null && root.right == null) {
            result += Integer.parseInt(paths.toString());
            return;
        }
        if (root.left != null) { // 左
            traversal(root.left, paths);
            paths.deleteCharAt(paths.length() - 1);// 回溯
        }
        if (root.right != null) { // 右
            traversal(root.right, paths);
            paths.deleteCharAt(paths.length() - 1);// 回溯
        }
    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
